package com.example.demo.exchange.mq.ibmmq.factory;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.example.demo.exchange.exception.UnsupportedMessageTypeException;
import com.example.demo.exchange.mq.MyMessage;
import com.example.demo.exchange.mq.ibmmq.mymessage.MessageOne;
import com.example.demo.exchange.mq.ibmmq.mymessage.MessageThree;
import com.example.demo.exchange.mq.ibmmq.mymessage.MessageTwo;

public class MessageFactory {
	public static final Map<Short, Class<?>> SUPPORED_CODES = new HashMap<Short, Class<?>>();
	private final static Logger logger = LoggerFactory.getLogger(MessageFactory.class);


	static {
		
		SUPPORED_CODES.put(MessageOne.CODE, MessageOne.class);
		SUPPORED_CODES.put(MessageTwo.CODE, MessageTwo.class);
		SUPPORED_CODES.put(MessageThree.CODE, MessageThree.class);
		
	}

	
	public static MyMessage create(String context,short code) {
		
			if (SUPPORED_CODES.containsKey(code)) {
				MyMessage message = null;
				try {
					 message = (MyMessage) SUPPORED_CODES.get(code).newInstance();
				} catch (InstantiationException | IllegalAccessException e) {
					logger.error("消息转换出错出错："+e);
					throw new IllegalArgumentException("new instance error");
				}
				message.analysis(context);
				return message;
			} else {
				logger.error("所解析的消息code {}不存在！", code);
				throw new UnsupportedMessageTypeException(
						"Not supported by Me!");
			}
		}
	}

	
	
